package jfdi;

import util.Mlog;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.JsonReader;

import java.io.IOException;

public class Label extends Node {

    String mLabel;
    Rect mTextBounds;
    float mTextLeft;
    float mTextBase;
    float mBaseFromCenter;

    public Label(NodeHost host) {
        super(host);
        init();
    }

    @Override
    protected void init() {
        super.init();
        mTextBounds = new Rect();
        setFontSize(24);
        mPaint.setTextAlign(Align.LEFT);
    }

    public void setText(String txt) {
        mLabel = txt;
        updateTextState();
    }

    public String getText() {
        return mLabel;
    }

    public void setFont(Typeface tf) {
        mPaint.setTypeface(tf);
        updateTextState();
    }

    public void setFontSize(float s) {
        mPaint.setTextSize(s);
        updateTextState();
    }

    private void updateTextState() {
        if (mLabel != null) {
            FontMetrics fm = mPaint.getFontMetrics();
            // top is negative
            mBaseFromCenter = (- fm.top - fm.bottom) / 2f;
//            Mlog.i(TAG, " top ", fm.top, " bottom ", fm.bottom, " base from center ",mBaseFromCenter);
            mPaint.getTextBounds(mLabel, 0, mLabel.length(), mTextBounds);
            layout(mLeft, mTop, mRight, mBottom);
        }
    }

    @Override
    public void layout(int l, int t, int r, int b) {
        super.layout(l, t, r, b);
        mTextLeft = (r - l - mTextBounds.width()) / 2f;
        mTextBase = (b - t) / 2f + mBaseFromCenter;
    }

    @Override
    public void render(Canvas canvas) {
        super.render(canvas);
        if (mLabel != null) {
            mPaint.setColor(mFgColor);
            canvas.drawText(mLabel, mTextLeft, mTextBase, mPaint);
        }
    }

    
    public void setAttribute(NodeHost host, String attr, JsonReader reader)
            throws IOException {
        if ("text".equals(attr)) {
            setText(reader.nextString());
        } else if ("textsize".equals(attr)) {
            setFontSize(reader.nextInt());
        } else {
            super.setAttribute(host, attr, reader);
        }
    }


}
